<?php

// Basado en los metodos de Zend_Controller_Action_Helper_ContextSwitch para JsonContext
class Ext_Context_CSV {

    protected $controller;

    protected $_db;

    public function __construct( $controller ) {
        $this->controller = $controller;
        $this->_db = $this->controller->getDb();
    }

    /**
     * CSV context extra initialization
     *
     * Turns off viewRenderer auto-rendering
     * 
     * @return void
     */
    public function initCsvContext() {
        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper( 'viewRenderer' );
        $view = $viewRenderer->view;
        if ( $view instanceof Zend_View_Interface ) {
            $viewRenderer->setNoRender( true );
        }
    }

    /**
     * CSV post processing
     *
     * @return void
     */
    public function postCsvContext() {

        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper( 'viewRenderer' );
        $view = $viewRenderer->view;
        if ( $view instanceof Zend_View_Interface ) {
            $vars = $view->getVars();
            if ( ! isset( $vars[ "csvData" ] ) ) {
                throw new Exception( "postCsvContext must set csvData" );
            }
            $csvData = $vars[ "csvData" ];
            if ( isset( $vars[ "csvTitle" ] ) ) {
                $csvTitle = $vars[ "csvTitle" ];
            } else {
                $csvTitle = false;
            }

            // parseamos el CSV y lo vamos mandando linea por linea.
            $csv = new Ext_Utils_CSV( $csvData, $csvTitle );
            while ( $line = $csv->getNextLine() )
            {
                $this->controller->getResponse()->setBody( $line );
                $this->controller->getResponse()->outputBody();
            }
            $this->controller->getResponse()->clearBody( );
        }
    }

}
